#!/usr/bin/env node

//Routes File

'use strict'

/* MODULE IMPORTS */
const Router = require('koa-router');
const userSession = require('../lib/userSessionUnit');
//const jimp = require('jimp')

/* IMPORT CUSTOM MODULES */
const items = require('../modules/itemsModules');
const apiResult = require('../modules/apiResult');

const router = new Router();

/**
 * The secure home page.
 *
 * @name Home Page
 * @route {GET} /
 * @authentication This route requires cookie-based authentication.
 */
router.get('/main', async ctx => {
	try {
		const data = {}
		if (ctx.query.msg) data.msg = ctx.query.msg;

		var user = userSession.getUserSession(ctx);
		await ctx.render('main', { user: user });
	} catch (err) {
		await ctx.render('error', { message: err.message })
	}
});

router.post('/main/addItem', async ctx => {
	let userId = userSession.getUserId(ctx);
	
	const body = ctx.request.body;
	
	await items.addItemAsync(userId, body.name, body.photo, body.description, body.swapItems);

	return ctx.body = new apiResult(true, 'save success', {});
});

router.post('/main/delItem', async ctx => {
	let userId = userSession.getUserId(ctx);
	
	const body = ctx.request.body;
	
	await items.deleteItemAsync(userId, body.id);

	return ctx.body = new apiResult(true, 'delete success', {});
});

router.get('/main/getMyItems', async ctx =>{
	let userId = userSession.getUserId(ctx);
	
	let pageIndex = ctx.query.pageIndex || 1;
	let pageSize = ctx.query.pageSize || 10;
	
	let result = await items.getItemListAsync(userId, pageIndex, pageSize);

	return ctx.body = new apiResult(true, 'get my items success', result);
});

router.post('/main/swapItem', async ctx =>{
	try {
		let targetItemId = ctx.request.body.targetItemId;
		let offerItemId = ctx.request.body.offerItemId;
		let offerDetail = ctx.request.body.offerDetail;

		await items.swapItemAsync(targetItemId, offerItemId, offerDetail);

		return ctx.body = new apiResult(true, 'Make an office success.');
	} catch (e) {
		return ctx.body = new apiResult(false, e);
	}
});

router.post('/main/saveIWant', async ctx=>{
	let userId = userSession.getUserId(ctx);
	let data = ctx.request.body.items;

	await items.saveIWantAsync(userId, data);

	return ctx.body = new apiResult(true, 'save success.');
});

router.get('/main/getIWant', async ctx=>{
	let userId = userSession.getUserId(ctx);

	let data =  await items.getIWantAsync(userId);

	return ctx.body = new apiResult(true, 'get success.', data);
});

router.get('/main/getWantedItems', async ctx=>{
	let data =  await items.getWantedItemsAsync();

	return ctx.body = new apiResult(true, 'get success.', data);
});

module.exports = router;
